package com.hxci.pointmap.controller;

import com.hxci.pointmap.utils.CaptchaUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@WebServlet("/captcha")
public class CaptchaServlet extends HttpServlet {

    private static final int WIDTH = 120;
    private static final int HEIGHT = 40;
    private static final int CODE_LENGTH = 4;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 生成随机验证码
        String code = CaptchaUtil.generateRandomCode(CODE_LENGTH);

        // 将验证码存入session
        HttpSession session = req.getSession();
        session.setAttribute("captcha", code);

        // 生成验证码图片
        BufferedImage image = CaptchaUtil.generateImage(code, WIDTH, HEIGHT);

        // 设置响应头
        resp.setContentType("image/jpeg");
        resp.setHeader("Cache-Control", "no-cache, no-store");
        resp.setHeader("Pragma", "no-cache");

        // 输出图片
        CaptchaUtil.outputImage(image, resp.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
